package com.example.ai.service.impl;

import com.example.ai.dto.PasswordUpdateDTO;
import com.example.ai.dto.UserProfileDTO;
import com.example.ai.exception.BusinessException;
import com.example.ai.model.User;
import com.example.ai.repository.UserRepository;
import com.example.ai.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

@Service
@RequiredArgsConstructor
public class UserServiceImpl implements UserService {

    private final UserRepository userRepository;
    private static final String UPLOAD_DIR = "uploads/avatars";

    @Override
    public UserProfileDTO getUserProfile(String username) {
        User user = userRepository.findByUsername(username)
                .orElseThrow(() -> new BusinessException("用户不存在"));
        
        UserProfileDTO profileDTO = new UserProfileDTO();
        BeanUtils.copyProperties(user, profileDTO);
        return profileDTO;
    }

    @Override
    @Transactional
    public UserProfileDTO updateUserProfile(String username, UserProfileDTO profileDTO) {
        User user = userRepository.findByUsername(username)
                .orElseThrow(() -> new BusinessException("用户不存在"));

        // 验证邮箱和手机号是否被其他用户使用
        if (profileDTO.getEmail() != null && 
            !profileDTO.getEmail().equals(user.getEmail()) && 
            userRepository.existsByEmailAndIdNot(profileDTO.getEmail(), user.getId())) {
            throw new BusinessException("该邮箱已被使用");
        }

        if (profileDTO.getPhone() != null && 
            !profileDTO.getPhone().equals(user.getPhone()) && 
            userRepository.existsByPhoneAndIdNot(profileDTO.getPhone(), user.getId())) {
            throw new BusinessException("该手机号已被使用");
        }

        // 更新用户信息
        user.setEmail(profileDTO.getEmail());
        user.setPhone(profileDTO.getPhone());
        
        user = userRepository.save(user);
        
        UserProfileDTO updatedProfile = new UserProfileDTO();
        BeanUtils.copyProperties(user, updatedProfile);
        return updatedProfile;
    }

    @Override
    @Transactional
    public void updatePassword(String username, PasswordUpdateDTO passwordDTO) {
        User user = userRepository.findByUsername(username)
                .orElseThrow(() -> new BusinessException("用户不存在"));

        // 验证原密码
        if (!user.getPassword().equals(passwordDTO.getOldPassword())) {
            throw new BusinessException("原密码错误");
        }

        user.setPassword(passwordDTO.getNewPassword());
        userRepository.save(user);
    }

    @Override
    public String uploadAvatar(String username, MultipartFile file) {
        User user = userRepository.findByUsername(username)
                .orElseThrow(() -> new BusinessException("用户不存在"));

        try {
            // 创建上传目录
            Path uploadPath = Paths.get(UPLOAD_DIR);
            if (!Files.exists(uploadPath)) {
                Files.createDirectories(uploadPath);
            }

            // 生成文件名
            String filename = UUID.randomUUID().toString() + getFileExtension(file.getOriginalFilename());
            Path filePath = uploadPath.resolve(filename);

            // 保存文件
            Files.copy(file.getInputStream(), filePath);

            // 更新用户头像路径
            String avatarUrl = "/api/uploads/avatars/" + filename;
            user.setAvatar(avatarUrl);
            userRepository.save(user);

            return avatarUrl;
        } catch (IOException e) {
            throw new BusinessException("头像上传失败");
        }
    }

    private String getFileExtension(String filename) {
        return filename.substring(filename.lastIndexOf("."));
    }
} 